package public

import (
	"crypto/sha1"
	"fmt"
	"io"
	"net/http"
	"rock/customer/initParam"
	"strconv"
	"strings"
	"time"
)

func RongCloudRequest(path, params string) (*http.Response, error) {

	//参数
	reader := strings.NewReader(params)

	//url
	host := initParam.RongCloudConf.Host
	rc_url := host + path
	req, err := http.NewRequest("POST", rc_url, reader)

	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	appKey := initParam.RongCloudConf.AppKey
	req.Header.Set("App-Key", appKey)

	//随机数
	nonce := RandomString(10)
	req.Header.Set("Nonce", nonce)
	//时间戳
	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	req.Header.Set("Timestamp", timestamp)
	//签名 （App Secret、Nonce (随机数)、Timestamp (时间戳)三个字符串按先后顺序拼接成一个字符串并进行 SHA1 哈希计算）
	appSecret := initParam.RongCloudConf.AppSecret
	//
	fmt.Println(fmt.Sprintf("Host => %v ;AppKey => %v ;AppSecret => %v",
		initParam.RongCloudConf.Host,
		initParam.RongCloudConf.AppKey,
		initParam.RongCloudConf.AppSecret))
	signatureString := appSecret + nonce + timestamp
	t := sha1.New()
	io.WriteString(t, signatureString)
	signature := fmt.Sprintf("%x", t.Sum(nil))
	req.Header.Set("Signature", signature)

	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	//defer response.Body.Close()

	return response, nil

}
